package tree.递归.剑指;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName N剑指Offer二叉搜索树与双向链表36.java
 * @Description  https://leetcode-cn.com/problems/er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/
 * @createTime 2021年03月29日 12:53:00
 */
public class N剑指Offer二叉搜索树与双向链表36 {
    class Node {
        public int val;
        public Node left;
        public Node right;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right) {
            val = _val;
            left = _left;
            right = _right;
        }
    }


    Node head  , pre;

    public Node treeToDoublyList(Node root) {
        if (root == null) {
            return root;
        }
        dfs(root);
        head.left= pre;
        pre.right=head;
        return head;
    }

    private void dfs(Node root) {
        if (root == null) {
            return;
        }
        dfs(root.left);
        //todo 如果前一个节点不为空，说明还在遍历左节点，如果前一个节点为null，说明左子树遍历完了，当前的root就是根节点了。
        if (pre !=null){
            pre.right=root;
        }else {
            head= root;
        }
        root.left= pre;
        pre =root;
        dfs(root.right);
    }
}
